# 阶段1: 构建阶段
FROM node:20.19.0-alpine as builder

WORKDIR /app

# 复制 package 文件
COPY package*.json ./
RUN npm ci

# 复制源码
COPY . .

# 构建参数
ARG VITE_API_BASE_URL=/api
ARG VITE_APP_ENV=production
ARG VITE_APP_TITLE=字符串生成器

ENV VITE_API_BASE_URL=${VITE_API_BASE_URL}
ENV VITE_APP_ENV=${VITE_APP_ENV}
ENV VITE_APP_TITLE=${VITE_APP_TITLE}

# 构建应用
RUN npm run build

# 阶段2: 生产阶段
FROM nginx:alpine

# 安装 curl
RUN apk add --no-cache curl

# 复制 nginx 配置
COPY nginx.conf /etc/nginx/nginx.conf

# 复制构建结果
COPY --from=builder /app/dist /usr/share/nginx/html

# 创建环境变量文件
RUN echo "window.APP_CONFIG = {" > /usr/share/nginx/html/config.js && \
    echo "  API_BASE_URL: '${VITE_API_BASE_URL}'," >> /usr/share/nginx/html/config.js && \
    echo "  APP_ENV: '${VITE_APP_ENV}'," >> /usr/share/nginx/html/config.js && \
    echo "  APP_TITLE: '${VITE_APP_TITLE}'" >> /usr/share/nginx/html/config.js && \
    echo "};" >> /usr/share/nginx/html/config.js

# 健康检查
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD curl -f http://localhost/ || exit 1

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]